<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { fetchCreateGameConfig, fetchUpdateGameConfig } from '@/service/api/games/game-config';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import DictSelect from '@/components/custom/dict-select.vue';

defineOptions({
  name: 'GameConfigOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Games.GameConfig | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});


const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增小游戏配置',
    edit: '编辑小游戏配置'
  };
  return titles[props.operateType];
});

type Model = Api.Games.GameConfigOperateParams;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
      gameCode: '',
      gameName: '',
      gameDesc: '',
      gameIcon: '',
      gamePath: '',
      gameCategory: '',
      sortOrder: undefined,
      status: '',
      isEnabled: '',
      remark: '',
  };
}

type RuleKey = Extract<
  keyof Model,
  | 'gameId'
  | 'gameCode'
  | 'gameName'
  | 'gamePath'
>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  gameId: createRequiredRule('游戏ID不能为空'),
  gameCode: createRequiredRule('游戏编码（唯一标识）不能为空'),
  gameName: createRequiredRule('游戏名称不能为空'),
  gamePath: createRequiredRule('游戏路径不能为空'),
};

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  const { gameId, gameCode, gameName, gameDesc, gameIcon, gamePath, gameCategory, sortOrder, status, isEnabled, remark } = model;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateGameConfig({ gameCode, gameName, gameDesc, gameIcon, gamePath, gameCategory, sortOrder, status, isEnabled, remark });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateGameConfig({ gameId, gameCode, gameName, gameDesc, gameIcon, gamePath, gameCategory, sortOrder, status, isEnabled, remark });
    if (error) return;
  }

  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="800" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="游戏编码（唯一标识）" path="gameCode">
          <NInput v-model:value="model.gameCode" placeholder="请输入游戏编码（唯一标识）" />
        </NFormItem>
        <NFormItem label="游戏名称" path="gameName">
          <NInput v-model:value="model.gameName" placeholder="请输入游戏名称" />
        </NFormItem>
        <NFormItem label="游戏描述" path="gameDesc">
          <NInput
            v-model:value="model.gameDesc"
            :rows="3"
            type="textarea"
            placeholder="请输入游戏描述"
          />
        </NFormItem>
        <NFormItem label="游戏图标" path="gameIcon">
          <NInput
            v-model:value="model.gameIcon"
            :rows="3"
            type="textarea"
            placeholder="请输入游戏图标"
          />
        </NFormItem>
        <NFormItem label="游戏路径" path="gamePath">
          <NInput v-model:value="model.gamePath" placeholder="请输入游戏路径" />
        </NFormItem>
        <NFormItem label="游戏分类" path="gameCategory">
          <DictSelect v-model:value="model.gameCategory" dict-code="game_category" placeholder="请选择游戏分类" immediate />
        </NFormItem>
        <NFormItem label="显示顺序" path="sortOrder">
          <NInput v-model:value="model.sortOrder" placeholder="请输入显示顺序" />
        </NFormItem>
        <NFormItem label="状态（0正常 1停用）" path="status">
          <NInput v-model:value="model.status" placeholder="请输入状态（0正常 1停用）" />
        </NFormItem>
        <NFormItem label="是否启用（0禁用 1启用）" path="isEnabled">
          <NInput v-model:value="model.isEnabled" placeholder="请输入是否启用（0禁用 1启用）" />
        </NFormItem>
        <NFormItem label="备注" path="remark">
          <NInput
            v-model:value="model.remark"
            :rows="3"
            type="textarea"
            placeholder="请输入备注"
          />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
